package selef.xiafan.service.impl;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import selef.xiafan.dao.StockDao;
import selef.xiafan.entity.system.Stock;
import selef.xiafan.query.StockQuery;
import selef.xiafan.service.IStockService;
import selef.xiafan.util.result.PageResult;

import java.util.List;

/**
 * @author xiafan
 * @version 1.0
 * @date 2021/7/21 23:13
 */
@Service
public class IStockServiceImpl implements IStockService {
    @Autowired
    private StockDao stockDao;

    @Override
    public PageResult<Stock> listStock(StockQuery stockQuery) {
        Integer page = (stockQuery.getPage() - 1) * stockQuery.getSize();
        Integer size = stockQuery.getSize();
        String nameForQuery = stockQuery.getName();

        if(nameForQuery==null||nameForQuery==""){
            Long total = stockDao.countAll();
            if (total == 0L) {
                return new PageResult<>();
            }
            List<Stock> stockListInDB = stockDao.findAllNoQuery(page, size);
            return new PageResult<>(total, stockListInDB);
        }
        Long total = stockDao.countAllByQuery(nameForQuery);
        List<Stock> stockListInDB = stockDao.findAllByQuery(page,size,nameForQuery);
        return new PageResult<>(total,stockListInDB);
    }

    @Override
    public Integer addOrEdit(Stock stock) {
        String stockId = stock.getStockId();
        // 判断对象中是否存在id值
        if (stockId == "") {
            stock.setStockId(RandomStringUtils.randomAlphanumeric(10));
            stock.setEnable(false);
            stock.setRemainAmount(stock.getPurchaseNum());
            stockDao.save(stock);
            return 1;
        }
        if (stockId != "") {
            stockDao.save(stock);
            return 2;
        }
        return 3;
    }

    @Override
    public Integer changeEnable(Stock stock) {
        Stock stockInDb = stockDao.findByStockId(stock.getStockId());
        if (stockInDb.getEnable()) {
            stockInDb.setEnable(false);
            stockDao.save(stockInDb);
            return 1;
        } else if (!stockInDb.getEnable()) {
            stockInDb.setEnable(true);
            stockDao.save(stockInDb);
            return 2;
        }
        return 3;
    }

    @Override
    @Transactional
    public void deleteByStock(Stock stock) {
        stockDao.deleteByStockId(stock.getStockId());
    }

    @Override
    public List<Stock> enabledStockList() {
        List<Stock> stockDAllByEnable = stockDao.findAllByEnable(true);
        return stockDAllByEnable;
    }
}
